<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/25
 * Time: 15:42
 */

namespace app\api\controller;


use app\api\model\TripActiveHotel;
use think\Controller;
use think\db;
use think\Log;
use app\api\model\Standard as SDModel;
use app\wap\controller\Notify;
use think\Request;


class Trip extends Controller
{
    /**组装自动建单数据
     * @param int $tripid 行程id
     * @param int $submitAdmin 后台操作员id【当后台用户发起建单是生效】 -1默认用户自主下单
     * @return array|string
     */
    public function getAutoCreateOrderData($tripid=0,$member,$statusData,$submitAdmin=-1)
    {
        $tripid = !empty($tripid)?$tripid:input('id');
        $trip = db('trip t')
            ->field('t.adminid as adminId,t.kbx_order_id as _id,t.id,t.name as tripName,t.introduction,t.people,t.adult,t.child,t.days,t.start_city as fromCityId,
            t.careful as careNote,t.back as returnRules,t.price as costsInclude,t.priceno as costsNotInclude,t.carType,t.start_go_time,
            t.costCurrency,t.section_json,t.section_trans_json,t.car_price_section,t.activitiesSnap,t.isLocked,t.isPaid,t.isConfirm,t.content as note,
                c.name as fromCityName,c.kbx_id as fromCityKbxId,insuranceDetail,
            totalAirportPrice_rate,totalHotelPrice_rate,totalDrivePrice_rate,
            totalTransPrice_rate,totalTicketPrice_rate,insurancePrice_rate,
            totalExtraPrice_rate,totalAirportPrice as airportCostPrice,
            insurancePrice,totalHotelPrice as hotelCostPrice,
            totalDrivePrice as driveCostPrice,totalTicketPrice as ticketCostPrice,
            totalExtraPrice as extraCostPrice,totalTransPrice as transCostPrice,
            total_price as costBase,total_sale_price as totalSalePrice')
            ->join('city c','c.id=t.start_city','left')
            ->where(['t.id'=>$tripid])
            ->find();
        if(empty($trip)) return [];
        //检测订单系统id未赋值 说明未推送到订单系统 去除_id字段
        if(empty($trip['_id'])) unset($trip['_id']);

        $trip['orderType'] = 'CustomMade';//定制类型
        $trip['typesource'] = 'myself';//自有
        $trip['startDate'] = date("Y-m-d",$trip['start_go_time']);//出发日期
        $schedules = db('schedule')
            ->where(['groupid'=>$tripid])
            ->field('id,time,title,displayorder')
            ->order('displayorder')
            ->select();
        if(empty($schedules)) return [];
        $schedule_ids = array_column($schedules,'id');
        $activeList = db('active a')
            ->join("city c", "c.id=a.cityid", 'left')
            ->join("poi p", "p.id=a.poiid", 'left')
            ->field("a.id,a.title,a.groupid,a.activeType,a.self_supplier_ticket,
            a.time as startingTime,a.content as remark,a.displayorder,
            a.poiid,a.cityid as cityId,c.name as cityName,
            c.kbx_id as kbxCityId,a.airport_lat,a.airport_lng,
            p.lat,p.lng,p.name as poiname,p.address,
            p.place_id,a.ticket_status,a.ticket_json,a.flight")
            ->where(['a.groupid' => ['in', $schedule_ids]])
            ->order('a.groupid,a.displayorder')
            ->select();
        if(empty($activeList)) return [];
        //获取分段信息
        $trip = $this->getProductSection($trip,$schedules,$activeList);
        //获取酒店和机场信息
        $trip = $this->getHotelAndAirportData($trip,$schedules,$activeList);

        //需要删除的字段
        $unset_field = [
            'section_json','car_price_section','activitiesSnap','section_trans_json',
            'totalAirportPrice_rate','insurancePrice_rate','totalHotelPrice_rate',
            'totalTicketPrice_rate','totalTransPrice_rate','totalDrivePrice_rate','totalExtraPrice_rate',
            'airportCostPrice','insurancePrice','hotelCostPrice','extraCostPrice',
            'ticketCostPrice','transCostPrice','driveCostPrice',
            'insuranceDetail','start_go_time'
        ];
        foreach ($unset_field as $field){
            unset($trip[$field]);
        }
        //组合用户信息和行程信息
        $trip = $this->packageCustomInfo($trip);
        $trip['submitAdmin'] = $submitAdmin;
        $trip['payType'] = 9;//后台建单 用户线下支付【直接转账到其他账号】
        $trip['isDelete'] = 0;//下单重新显示订单【订单系统为覆盖赋值】
        //增加预定人信息
        $trip = $this->addBookerCustomInfo($trip,$member);
        //整合订单状态
        $trip = array_merge($trip,$statusData);
        return $trip;
    }

    //获取行程信息
    public function getProductSection($productInfo,$schedules,$activeList)
    {
        foreach ($schedules as $key=>$value){
            $schedules[$key]['label'] = "第".$value['displayorder']."天";
            $schedules[$key]['children'] = [];
            foreach ($activeList as $k=>$v){
                $v = (new SDModel())->getAirportInfo($v);
                if($v['groupid']==$value['id']){
                    $v['label'] = empty($v['poiname'])?$v['title']:$v['poiname'];
                    //准备经纬度
                    if(in_array($v['activeType'],[2,3])){
                        $v['lat'] = $v['airport_lat'];
                        $v['lng'] = $v['airport_lng'];
                    }
                    unset($v['airport_lat'],$v['airport_lng']);
                    $schedules[$key]['children'][] = $v;
                }
            }
        }
        //$productInfo['tripData'] = $schedules;
        //筛选行程的起点和终点
        $start_poi = $end_popi = [];
        foreach ($schedules as $key=>$value){
            foreach ($value['children'] as $k=>$v){
                if(!empty($v['lat']) && !empty($v['lng'])){
                    if(empty($start_poi)){
                        $start_poi = $v;
                    }
                    $end_popi = $v;
                }
            }
        }
        $from = $to = new \ArrayObject();
        if(!empty($start_poi)){
            $from = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$start_poi['label'],
                        "addr"=>$start_poi['address'],
                        "lat"=>$start_poi['lat'],
                        "lng"=>$start_poi['lng'],
                        "gid"=>$start_poi['place_id'],
                    ]
                ]
            ];
        }
        if(!empty($end_popi)){
            $to = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$end_popi['label'],
                        "addr"=>$end_popi['address'],
                        "lat"=>$end_popi['lat'],
                        "lng"=>$end_popi['lng'],
                        "gid"=>$end_popi['place_id'],
                    ]
                ]
            ];
        }
        $productInfo['from'] = $from;
        $productInfo['to'] = $to;
        //平台自采门票
        $selfTickets = [];

        $section_json = json_decode($productInfo['section_json'],true);
        $car_price_section = json_decode($productInfo['car_price_section'],true);
        $section_json = !empty($section_json)?$section_json:[];
        $car_exchange = db('exchange')->where(['currency_code'=>$productInfo['costCurrency']])->find();
        if(!empty($section_json)){
            $section = [];
            foreach ($section_json as $section_k=>$section_v){
                $exchange_rate = $car_exchange['exchange_rate']??1;
                $amount = $car_price_section[$section_k]??0;
                $amountCNY = ceil($amount*$exchange_rate);
                $carPrice = ceil($amount*$exchange_rate*$productInfo['totalTransPrice_rate']);
                $carBase = [
                    'amount'=>$amount,
                    'amountCNY'=>$amountCNY,
                    'currency'=>$productInfo['costCurrency']
                ];
                $section[] = $this->packageSectionDataPricing($section_v,$schedules,$productInfo['carType'],$carPrice,$carBase,$productInfo['totalTransPrice_rate'],$productInfo['totalTicketPrice_rate']);
            }

            //将自采的门票的司机采购的门票分开
            $selfTickets = $this->getSelfTickets($section);
            $day_sort = array_column($section,'day');
            array_multisort($section,SORT_ASC,$day_sort);
            $productInfo['subclassOrders']['sections'] = $section;
        }else{
            $productInfo['subclassOrders']['sections'] = [];
        }
        $productInfo['subclassOrders']['tickets'] = $selfTickets;
        //删除交通配置json数据【接口不需要显示】
        //unset($productInfo['section_json']);
        unset($productInfo['section_trans_json']);
        return $productInfo;
    }
    //将自采门票和司导采购门票分开
    public function getSelfTickets($section)
    {
        $poiTickets = [];
        //将自采的门票的司机采购的门票分开
        foreach ($section as $s_k=>$s_v){
            if(!empty($s_v['tickets'])){
                foreach ($s_v['tickets'] as $t_k=>$t_v){
                    if(!$t_v['include']){
                        $this->caculatePoiTickets($poiTickets,$t_v);
                    }
                }
            }
        }
        $poiTickets = array_values($poiTickets);//重新建立索引
        return $poiTickets;

    }
    //计算门票信息
    public function caculatePoiTickets(&$tickets,$ticket_value)
    {
        if(isset($tickets[$ticket_value['poiId']])){
            $tickets[$ticket_value['poiId']]['tickets'][] = $ticket_value;
            $tickets[$ticket_value['poiId']]['costPrice'] += $ticket_value['ticketNumber']*$ticket_value['unitCostPrice'];
            $tickets[$ticket_value['poiId']]['totalPrice'] += $ticket_value['ticketNumber']*$ticket_value['unitPrice'];
            $tickets[$ticket_value['poiId']]['totalNum'] += $ticket_value['ticketNumber'];
            $tickets[$ticket_value['poiId']]['cost']['amount'] += $ticket_value['unitBase']['amount']*$ticket_value['ticketNumber'];
        }else{
            $tickets[$ticket_value['poiId']] = [
                'id'=>$ticket_value['poiId'],
                'startDate'=>$ticket_value['startDate'],
                'kbxCityId'=>$ticket_value['kbxCityId'],
                'poiName'=>$ticket_value['poiName'],
                'saleRate'=>$ticket_value['saleRate'],
                'costPrice'=>$ticket_value['ticketNumber']*$ticket_value['unitCostPrice'],
                'totalPrice'=>$ticket_value['ticketNumber']*$ticket_value['unitPrice'],
                'totalNum'=>$ticket_value['ticketNumber'],
                'cost'=>[
                    'amount'=>$ticket_value['unitBase']['amount']*$ticket_value['ticketNumber'],
                    'currency'=>$ticket_value['unitBase']['currency'],
                ],
                'tickets'=>[$ticket_value]
            ];
        }
    }

    //封装单个section 用于用于拆单
    public function packageSectionDataPricing($trans_value,$schedules,$carType,$carPrice,$carBase,$carSaleRate,$ticketSaleRate)
    {
        //当前段的包车类型 默认是市内一日包车
        $transport_type = empty($trans_value['transport'])?4:$trans_value['transport'];
        $subType = (new SDModel())->getTransportType($transport_type);

        //当前段的包车报价
        $start_index = explode("-",$trans_value['start']);
        $end_index = explode("-",$trans_value['end']);
        $section = [];
        $poiList = [];
        if($start_index[0]==$end_index[0]){
            $child = $schedules[$start_index[0]]['children'];
            $length = $end_index[1]-$start_index[1]+1;
            $activeList = array_slice($child,$start_index[1],$length);
            $scheduleList = $schedules[$start_index[0]];
            $scheduleList['children'] = $activeList;
            $section[] = $scheduleList;
            $poiList = $activeList;
        }else{
            for ($i = $start_index[0]; $i <= $end_index[0]; $i++){
                $child = $schedules[$i]['children'];
                if($i < $end_index[0]){
                    $max = count($child);
                    $scheduleList = $schedules[$i];
                    if($i > $start_index[0]){
                        $activeList = array_slice($child,0,$max);
                    }else{
                        $activeList = array_slice($child,$start_index[1],$max);
                    }
                    $poiList += $activeList;
                    $scheduleList['children'] = $activeList;
                }else{
                    $activeList = array_slice($child,0,$end_index[1]+1);
                    $scheduleList = $schedules[$i];
                    $poiList += $activeList;
                    $scheduleList['children'] = $activeList;
                }
                $section[] = $scheduleList;
            }
        }
        //获取标题
        $title = "";
        //门票信息
        $ticket = [];
        foreach ($section as $key=>$value){
            $title .= "第".$value['displayorder']."天:";
            $active_title = array_column($value['children'],"label");
            if(!empty($active_title)){
                $title .= implode("--",$active_title);
            }
            $title .= "\n";

            foreach ($value['children'] as $child_k=>$child_v){
                //启用的门票 配置了购买张数
                if($child_v['ticket_status']==1 && !empty($child_v['ticket_json'])){
                    $ticketList = $this->getSectionTicketData($child_v['ticket_json'],$ticketSaleRate,$child_v['self_supplier_ticket'],$value['time']);
                    $ticket = array_merge($ticket,$ticketList);
                }
            }
        }
        //获取起始点和终点的经纬度
        $start_poi = $end_poi = [];
        foreach ($poiList as $key=>$value){
            if(!empty($value['lat']) && !empty($value['lng'])){
                if(empty($start_poi)){
                    $start_poi = $value;
                }
                $end_poi = $value;
            }
        }
        $fromKbxCityId = "";
        $from = $to = new \ArrayObject();
        if(!empty($start_poi)){
            $from = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$start_poi['label'],
                        "addr"=>$start_poi['address'],
                        "lat"=>$start_poi['lat'],
                        "lng"=>$start_poi['lng'],
                        "gid"=>$start_poi['place_id'],
                    ]
                ]
            ];
            $fromKbxCityId = $start_poi['kbxCityId'];
        }
        if(!empty($end_poi)){
            $to = [
                'arbitrary'=>[
                    'geocoded'=>[
                        "name"=>$end_poi['label'],
                        "addr"=>$end_poi['address'],
                        "lat"=>$end_poi['lat'],
                        "lng"=>$end_poi['lng'],
                        "gid"=>$end_poi['place_id'],
                    ]
                ]
            ];
        }
        $startDay = intval(explode("-",$trans_value['start'])[0]);
        return [
            'startDay'=>$startDay,
            'carType'=>$carType,
            'orderType'=>"Vehicle",
            'day'=>$trans_value['start'],
            'from'=>$from,
            'to'=>$to,
            'orderSubType'=>$subType,
            'toursLineTitle'=>$title,
            'fromCity'=>$fromKbxCityId,
            'days'=>count($section),
            'tickets'=>$ticket,
            'carPrice'=>$carPrice,
            'saleRate'=>$carSaleRate,
            'carBase'=>$carBase,
        ];
    }

    //获取产品关联的门票信息
    public function getSectionTicketData($ticket_json,$ticket_sale_rate,$self_supplier_ticket=0,$startDate='')
    {
        $ticket = [];
        $exchangeArr = db("exchange")->select();//汇率
        if(!empty($ticket_json)){
            $ticket_arr = json_decode($ticket_json,true);
            $ticket_ids = array_column($ticket_arr,'ticket_id');
            if(empty($ticket_ids)) return [];
            $ticketPriceData = db("ticketprice tp")
                ->join("poi p","p.id=tp.poiid",'left')
                ->join("city c","c.id=p.groupid",'left')
                ->where(['tp.id'=>['in',$ticket_ids]])
                ->field("tp.id,tp.name,tp.sale_price,tp.cost_price,tp.currency,p.id as poiid,
                    p.name as poiname,p.eng_name as poiengname,c.kbx_id")
                ->select();
            foreach ($ticketPriceData as $ticket_v){
                $ticket_people = 0;
                foreach ($ticket_arr as $ticket_num){
                    if($ticket_v['id']==$ticket_num['ticket_id']){
                        $ticket_people = $ticket_num['number'];
                        break;
                    }
                }
                $exchangeRate = 1;
                foreach ($exchangeArr as $exchange){
                    if($exchange['currency_code']==$ticket_v['currency']){
                        $exchangeRate = $exchange['exchange_rate'];
                    }
                }
                $ticket[] = [
                    'ticketId'=>$ticket_v['id'],
                    'startDate'=>$startDate,
                    'poiId'=>$ticket_v['poiid'],
                    'kbxCityId'=>$ticket_v['kbx_id'],
                    'include'=>$self_supplier_ticket==1?false:true,
                    'poiName'=>$ticket_v['poiname'].'('.$ticket_v['poiengname'].')',
                    'ticketName'=>$ticket_v['name'],
                    'ticketNumber'=>$ticket_people,
                    'saleRate'=>$ticket_sale_rate,
                    'unitBase'=>[
                        'amount'=>$ticket_v['cost_price'],
                        'currency'=>$ticket_v['currency'],
                    ],
                    'unitCostPrice'=>ceil($ticket_v['cost_price']*$exchangeRate),
                    'unitPrice'=>ceil($ticket_v['cost_price']*$exchangeRate*$ticket_sale_rate),
                    'desc'=>"",
                ];
            }
        }
        return $ticket;
    }
    //获取酒店的报价信息
    public function getHotelAndAirportData($trip,$schedule,$activeList)
    {
        $trip['subclassOrders']['hotels'] = [];
        $schedule_ids = array_column($schedule,'id');
        $dayprice = db("dayprice dp")
            ->join('schedule s','s.id=dp.groupid','left')
            ->field('dp.*,s.time as day')
            ->where(['dp.groupid'=>['in',$schedule_ids]])
            ->order('s.time')
            ->select();
        //获取汇率
        $exchange = db('exchange')->select();
        $hotelData = [];
        $prev_time = 0;
        $prev_poi = 0;
        foreach ($dayprice as $day_key=>$day_value){
            $hotelInfo = [];
            if(!empty($day_value['hotelPrice'])){
                //当天的最后一个酒店节点
                $hotelInfo = db('active a')
                    ->join("city c", "c.id=a.cityid", 'left')
                    ->join("poi p", "p.id=a.poiid", 'left')
                    ->join("schedule s", "a.groupid=s.id", 'left')
                    ->field("s.id,s.time,a.title,a.cityid as cityId,a.poiid,
                            c.name as cityName, c.kbx_id as kbxCityId,c.groupid as city_groupid,
                            p.lat,p.lng,p.name as poiname,p.address,p.place_id")
                    ->where(['a.activeType'=>4,'a.groupid'=>$day_value['groupid']])
                    ->order('a.displayorder desc')
                    ->find();
                if(empty($hotelInfo)) continue;
                if((strtotime($hotelInfo['time'])-3600*24)==$prev_time && $hotelInfo['poiid']==$prev_poi){
                    $index = count($hotelData)-1;
                    $hotelData[$index]['dayNum'] = $hotelData[$index]['dayNum']+1;
                    $hotelData[$index]['endDate'] = date("Y-m-d",strtotime('+1 day',strtotime($hotelData[$index]['endDate'])));
                    //更新上一天的时间
                    $prev_time = strtotime($hotelInfo['time']);
                    continue;
                }else{
                    $hotelInfo['dayNum'] = 1;
                    $hotelInfo['endDate'] = date("Y-m-d",strtotime('+1 day',strtotime($hotelInfo['time'])));
                }
                $hotelInfo['startDate'] = $hotelInfo['time'];
                $hotelInfo['saleRate'] = $trip['totalHotelPrice_rate'];
                $hotelInfo['hotelDetail'] = $day_value['hotelDetail'];
                $hotelInfo['costPrice'] = $day_value['hotelPrice'];
                $hotelInfo['totalPrice'] = ceil($day_value['hotelPrice']*$hotelInfo['saleRate']);
                $hotelInfo['totalRoom'] = ceil($trip['people']/2);
                $hotelInfo['unitPrice'] = ceil($hotelInfo['totalPrice']/$hotelInfo['totalRoom']);
                $hotelInfo['totalPeople'] = $trip['people'];
                $hotelInfo['totalAdult'] = $trip['adult'];
                $hotelInfo['totalChild'] = $trip['child'];
                $hotelInfo['address'] = [
                    'arbitrary'=>[
                        'geocoded'=>[
                            "name"=>empty($hotelInfo['poiname'])?$hotelInfo['title']:$hotelInfo['poiname'],
                            "addr"=>$hotelInfo['address'],
                            "lat"=>$hotelInfo['lat'],
                            "lng"=>$hotelInfo['lng'],
                            "gid"=>$hotelInfo['place_id'],
                        ]
                    ]
                ];
                unset($hotelInfo['time'],
                    $hotelInfo['poiname'],
                    $hotelInfo['title'],
                    $hotelInfo['place_id'],
                    $hotelInfo['lat'],
                    $hotelInfo['lng']);

                $hotelData[] = $hotelInfo;
                //更新上一天的数据
                $prev_time = strtotime($hotelInfo['startDate']);
                $prev_poi = $hotelInfo['poiid'];
            }
        }
        //把相邻的酒店进行合并
        if(empty($hotelData)) $hotelData = [];
        foreach ($hotelData as $hotel_key=>$hotelInfo){
            //计算酒店的当地成本
            $currency_code = 'USD';
            if($hotelInfo['city_groupid']==51){
                $currency_code = 'CAD';
            }
            //查找汇率
            foreach ($exchange as $exchange_v){
                if($exchange_v['currency_code']==$currency_code){
                    $exchange_rate = $exchange_v['exchange_rate'];
                    break;
                }
            }
            $hotelInfo['cost']['amount'] = ceil($hotelInfo['totalPrice']/$exchange_rate);
            $hotelInfo['cost']['currency'] = $currency_code;
            $hotelData[$hotel_key] = $hotelInfo;
        }
        $trip['subclassOrders']['hotels'] = $hotelData;

        $trip = $this->getAirportData($trip,$activeList,$dayprice);
        //其他费用
        $trip = $this->getOtherFeeData($trip,$dayprice);
        return $trip;
    }
    //获取航班的报价信息
    public function getAirportData($trip,$activeList,$dayPrice)
    {
        $trip['subclassOrders']['flights'] = $airportList = $airportData = [];
        foreach ($activeList as $key=>$value){
            //筛选接送机类的节点
            if(in_array($value['activeType'],[2,3])){
                $airportList[$value['groupid']][] = $value;
            }
        }
        $airportPrice_rate = $trip['totalAirportPrice_rate'];
        foreach ($airportList as $active_key=>$active_value){
            foreach ($dayPrice as $day_value){
                if($day_value['groupid']==$active_key){
                    $airportJson = json_decode($day_value['airport_json'],true);
                    if(empty($airportJson)) continue;
                    foreach ($active_value as $ak=>$av){
                        $cost = $airportJson[$ak][2]??0;
                        $totalPrice = ceil($cost*$airportPrice_rate);
                        $airportData[] = [
                            'startDate'=>$day_value['day']??"",
                            'startTime'=>$av['startingTime']??"09:00",
                            'title'=>$av['title']??"",
                            'poiId'=>$av['poiid']??"",
                            'flightNo'=>$av['flight']??"",
                            'cityName'=>$av['cityName']??"",
                            'kbxCityId'=>$av['kbxCityId']??"",
                            'desc'=>$airportJson[$ak][1]??"",
                            'totalPrice'=>$totalPrice,
                            'saleRate'=>$airportPrice_rate,
                            'cost'=>[
                                'amount'=>$cost,
                                'currency'=>'CNY'
                            ]
                        ];
                    }
                    break;
                }
            }
        }
        $trip['subclassOrders']['flights'] = $airportData;
        return $trip;
    }

    //获取其他费用
    protected function getOtherFeeData($trip,$dayprice){
        $trip['subclassOrders']['insurance'] = $trip['subclassOrders']['extras'] = [];
        $insurancePrice_rate = $trip['insurancePrice_rate'];
        $extraPrice_rate = $trip['totalExtraPrice_rate'];
        foreach ($dayprice as $day_value){
            if(!empty($day_value['extraPrice'])){
                $trip['subclassOrders']['extras'][] = [
                    'totalPrice'=>ceil($extraPrice_rate*$day_value['extraPrice']),
                    'desc'=>$day_value['extraDetail'],
                    'saleRate'=>$extraPrice_rate,
                    'cost'=>[
                        'amount'=>$day_value['extraPrice'],
                        'currency'=>'CNY'
                    ]
                ];
            }
        }
        if(!empty($trip['insurancePrice'])){
            $trip['subclassOrders']['insurance'][] = [
                'totalPrice'=>ceil($trip['insurancePrice']*$insurancePrice_rate),
                'insuranceDetail'=>$trip['insuranceDetail'],
                'saleRate'=>$insurancePrice_rate,
                'cost'=>[
                    'amount'=>$trip['insurancePrice'],
                    'currency'=>'CNY'
                ],
            ];
        }

        return $trip;
    }

    //组装用户个人信息
    protected function packageCustomInfo($trip){
        $tripUser = db('tripcustomer')->where(['tripid'=>$trip['id']])->find();
        //是否包含区号
        $tripUser['country_code'] = $tripUser['country_code']??"+86";
        if(!empty($tripUser['phone'])){
            //手机号是否包含 +
            if(strpos($tripUser['phone'],'+')===false){
                $tripUser['phone'] = $tripUser['country_code'].$tripUser['phone'];
            }
        }
        $trip['contact'] = [//客户信息
                "name"=>isset($tripUser['nickname'])?$tripUser['nickname']:"",//客户姓名
                "phone"=>isset($tripUser['phone'])?$tripUser['phone']:"",//客户电话
                "wechat"=>isset($tripUser['wechat'])?$tripUser['wechat']:"",//客户微信号
                "email"=>isset($tripUser['email'])?$tripUser['email']:"",//客户邮箱
                "sex"=>isset($tripUser['sex'])?$tripUser['sex']:"",//客户性别
                "age"=>isset($tripUser['age'])?$tripUser['age']:"",//客户年龄
                "ageBand"=>isset($tripUser['ageBand'])?$tripUser['ageBand']:"",//客户年龄范围
                "description"=>isset($tripUser['description'])?$tripUser['description']:"",//客户描述
            ];
        $trip['bigGroup'] =isset($tripUser['type'])?($tripUser['type']=='team'):false;//出行类型 团体true 个人false
        $trip['origin'] = isset($tripUser['source'])?$tripUser['source']:"";//来源平台
        $trip['otaOrderId'] = isset($tripUser['ota_order_id'])?$tripUser['ota_order_id']:"";//来源平台
        $trip['note'] = isset($trip['note'])?$trip['note']:"";//备注
        $trip['paid'] = isset($trip['ispaid'])?$trip['paid']:false;//是否支付
        return $trip;
    }

    //增加预订人信息
    public function addBookerCustomInfo($trip,$member)
    {
        $trip['booker'] = [];
        if(empty($member)){
            return $trip;
        }

        if(isset($member['member_pcode']) && !empty($member['member_pcode'])){
            $pmember = db("member")->where("member_id",$member['member_pcode'])->find();
            if(!empty($pmember)){
                $pname =  $pmember['member_nickname'];
                $pphone =  $pmember['member_phone'];
                $premark =  $pmember['member_remark'];
            }
        }
        $trip['booker'] =  [//预订人
            "username" => $member['member_username'],
            "memberId" => $member['member_id'],//会员id
            "memberPCode" => $member['member_pcode']??null,//推荐人id
            "memberPName" => $pname??'',//推荐人昵称
            "memberPPhone" => $pphone??'',//推荐人电话
            "memberPRemark" => $premark??'',//推荐人备注
        ];
        return $trip;
    }
    //检查自动建单必须数据
    public function checkTripDataComplete($tripid)
    {
        $trip = db("trip t")
            ->join('tripcustomer tc','tc.tripid=t.id','left')
            ->field('t.*,tc.nickname as username,country_code,phone,email,source')
            ->where(['t.id'=>$tripid])
            ->find();
        if(empty($tripid) || empty($trip)) return "行程信息有误";
        //必须的数据
        //是否支付
        if(!empty($trip['isPaid'])) return "行程已支付";
        //1 行程信息
        if(empty($trip['people'])) return "请补充出行人数";
        if(empty($trip['start_go_time'])) return "请补充出行日期";
        if(empty($trip['start_city'])) return "请选择出发城市";
        if(empty($trip['carType'])) return "请选择用车车型";
        //2 客户信息
        if(empty($trip['username'])) return "请补充客户姓名";
        if(empty($trip['country_code'])) return "请补充客户联系方式的国家区号";
        if(empty($trip['phone'])) return "请补充客户联系方式";
        //if(empty($trip['email'])) return "请补充客户邮箱地址";
        if(empty($trip['source'])) return "请补充来源平台";
        //3 用车价格
        if(empty($trip['section_json']) || empty($trip['section_trans_json'])) return "请补充用车配置";
        if(empty($trip['total_sale_price'])) return "总售价为空";

        return $trip;
    }

    //实现建单过程
    public function pushCustomMadeOrder($trip,$member_id,$isPaid=false)
    {
        //查找是否存在已支付的相关订单
        $payOrder = db('custom_made_order')
            ->where(['trip_id'=>$trip['id'],'order_status'=>['egt',2]])
            ->find();
        if(!empty($payOrder)) return '该定制已支付,请勿重复支付！';

        //防止刷接口
        $lastTime = db('trip')
            ->field('kbx_last_time')
            ->where(['id'=>$trip['id']])
            ->find();
        //至少一分钟才能操作一次
        if(!empty($lastTime)){
            if((time() - $lastTime['kbx_last_time']) < 60 ) return '操作频繁,请一分钟后再试！';
        }
        //删除所有的待支付订单
        db('custom_made_order')
            ->where(['trip_id'=>$trip['id']])
            ->delete();
        //创建订单号
        //$prefix = "CM";
        //$order_no = $prefix.strtoupper(uniqid());
        db::startTrans();
        try{
            //推送订单到订单系统
            //pushCustomOrderDataToOrderSystem ...
            $kbx_res = (new KbxOrder())->pushCustomOrderDataToOrderSystem($trip);
            //$kbx_res['_id'] = md5(time());
            if(!isset($kbx_res['_id']) || !isset($kbx_res['orderNo'])){
                Log::write("推送定制订单失败",json_encode(['data'=>$trip,'result'=>$kbx_res]));
                return $kbx_res['msg']??"自动建单失败,请稍后重试！";
            }
            //创建未支付订单
            $userphone = strpos($trip['contact']['phone'],'+')!==false?$trip['contact']['phone']:"+".$trip['contact']['phone'];
            //推送的是未支付订单 order_status=1 已支付订单为order_status=2
            $order_status = $isPaid?2:1;
            $order_no = $kbx_res['orderNo'];
            db('custom_made_order')->insert([
                'order_no'=>$order_no,
                'member_id'=>$member_id,
                'trip_id'=>$trip['id'],
                'createtime'=>time(),
                'updatetime'=>time(),
                'travel_date'=>$trip['startDate'],
                'finished_condition'=>1,
                'contact_xing'=>'',
                'contact_ming'=>$trip['contact']['name'],
                'wechat_number'=>$trip['contact']['wechat'],
                'phone'=>$userphone,
                'fold_money'=>$trip['totalSalePrice'],
                'e_mail'=>$trip['contact']['email'],
                'order_status'=>$order_status,
                'orderSnap'=>json_encode($trip),
            ]);

            //返回kbx_id 更新kbx_id
            $order_id = db("custom_made_order")->getLastInsID();
            db('custom_made_order')->where(['id'=>$order_id])->update(['kbx_id'=>$kbx_res['_id']]);
            //后台建单 直接修改状态为已支付
            if($isPaid){
                $update_trip['isPaid'] = 1;
                $update_trip['isConfirm'] = 1;
            }
            $update_trip['kbx_order_id'] = $kbx_res['_id'];
            $update_trip['kbx_last_time'] = time();
            db('trip')->where(['id'=>$trip['id']])->update($update_trip);
            db::commit();
            //发送邮件
            //成功下单通知
            $orderDate = array(
                'tripid' => $trip['id'],
                'tripname' => $trip['tripName'],
                'member_id' => $member_id,
                'order_no' => $order_no,
                'e_mail' => $trip['contact']['email'],
                'phone' => $trip['contact']['phone'],
                "travel_date" => $trip['startDate'],
            );
            (new Notify())->gyouxiang($orderDate,'CustomMade');
            return [
                'order_id'=>$order_id,
                'order_no'=>$order_no,
                'order_type'=>'CustomMade',
                'kbx_order_id'=>$kbx_res['_id']
            ];
        }catch(Exception $e){
            db::rollback();
            return "下单失败,请稍后重试！";
        }
    }

    //获取定制结构数据【仅用于测试】
    public function getCustomMadeOrderData($id)
    {
        $member_id = "453";
        $member = db("member")->find($member_id);
        //后台直接下单的状态
        $statusData = [
            'statusPhp'=>[
                'orderStatus'=>1,//已支付状态
                'finishedCondition'=>0,//表单已完善
            ]
        ];
        $data = $this->getAutoCreateOrderData($id,$member,$statusData);
        return json_encode($data);
    }

    //获取后台账号的信息
    public function getAadminList()
    {
        $res = db('admin')->field('id,nickname,name')->select();
        return json_encode($res);
    }

    //小程序我的出行
    public function mytrip(){
        $post=request()->request();
        $tripid = $post['trip_id']??0;
        if(empty($tripid)) return json(['code'=>101,'msg'=>'数据为空']);

        $da=db('trip')
            ->where('id',$tripid)
            ->field('adminid,id as trip_id,price,priceno,name,description,
            introduction,days,people,back,careful,section_json,start_go_time,
            showback,showcareful,showprice,showintroduction,
            budget_price,trip_banner,show_day_map,show_city_map,showpricedetail,
            total_price,insurancePrice,insuranceDetail,
            totalHotelPrice,totalDrivePrice,totalTicketPrice,
            totalExtraPrice,totalTransPrice,totalAirportPrice,
            totalAirportPrice_rate,totalHotelPrice_rate,
            totalDrivePrice_rate,totalTransPrice_rate,
            totalTicketPrice_rate,insurancePrice_rate,
            totalExtraPrice_rate,total_sale_price,isPaid,isConfirm')
            ->find();
        $name=db('admin')->where('id',$da['adminid'])->field('nickname,wx_qrcode')->find();
        $da['admin_name']=$name['nickname'];
        //如果未上传微信二维码 则使用小美的微信二维码 12363
        $name['wx_qrcode'] = !empty($name['wx_qrcode'])?$name['wx_qrcode']:12363;
        $da['wx_qrcode'] = geturl($name['wx_qrcode'])??"";
        $da['isDrive'] = false;

        if ($da['showback']==0) $da['back']='';
        if ($da['showcareful']==0) $da['careful']='';

        if ($da['showprice']==0){
            $da['price']='';
            $da['priceno']='';
        }
        if ($da['showintroduction']==0) $da['introduction']='';
        if (empty($da)) return json_encode(['msg'=>'没有找到行程请联系客服人员','code'=>101]);

        $rc = db('schedule')
            ->where('groupid',$post['trip_id'])
            ->order('displayorder asc')
            ->field('id,time,title,transport_typeids')
            ->select();
        if (empty($rc)) json_encode(['msg'=>'没有日程安排','code'=>101]);
        if (count($rc)>1){
            $end= end($rc);
        }else{
            $end= $rc[0];
        }
        $top=$rc[0];
        $da['time']='--';
        if (!empty($top['time'])&&!empty($end['time'])){
            $da['time']= $top['time'].'--'.$end['time'];
        }
        if (empty($end['time'])){
            $da['time']= $top['time'];
        }

        $city_id=[];
        $da['city_name']='';
        $keyArr = array();//索引集合
        //开始遍历日程
        $allcitys = $allcityLatLngs = [];
        //判断是否拥有 美食等附加信息
        $hasExtra = false;
        foreach ($rc as $k=>$v){
            //判断是否存在自驾
            if(!empty($v['transport_typeids'])){
                $transport_typeid = explode(",",$v['transport_typeids']);
                if(in_array(7,$transport_typeid)){
                    $da['isDrive'] = true;
                }
            }

            $xq=db('active a')
                ->join("city c","c.id=a.cityid",'left')
                ->join("poi p","p.id=a.poiid",'left')
                ->field("a.*,c.lat as c_lat,c.lng as c_lng,p.introduce as p_introduce,p.lat,p.lng,p.thumb as poi_thumb,p.eng_introduce,p.open_time,p.ticket,p.price,p.grade,p.description,p.thumb,p.source,p.mobile,p.ticket_url,p.address")
                ->where('a.groupid',$v['id'])
                ->order('a.displayorder asc')
                ->select();

            $activeKeyArr = [];
            $activeTypeList = $this->getGlobalActiveTypeList(false);
            $includePoiActiveTypeList = $this->getGlobalActiveTypeList();
            //开始遍历节点
            foreach ($xq as $t=>$y){
                if(in_array($y['activeType'],$activeTypeList)){
                    $hasExtra = true;
                }
                //所有城市经纬度
                $cityLatLng = [
                    'lat'=>floatval($y['c_lat']),
                    'lng'=>floatval($y['c_lng'])
                ];
                if(end($allcityLatLngs)!=$cityLatLng){
                    array_push($allcityLatLngs,$cityLatLng);
                }
                //节点经纬度
                $rc[$k]['hasLine'] = false;
                $vo_start_poi=[];
                $vo_end_poi=[];
                $vo_ways_poi=[];
                $vo_latLng = [];
                if(count($xq)>=2 && $da['show_day_map']==1){
                    $vo_latLng = $xq;
                    foreach ($vo_latLng as $v_key=>$v_poi){
                        //判断开始的类型
                        if(in_array($v_poi['activeType'],[1,4,15])){
                            $vo_latLng[$v_key]['lat'] = $v_poi['lat'];
                            $vo_latLng[$v_key]['lng'] = $v_poi['lng'];
                        }elseif(in_array($v_poi['activeType'],[2,3])){
                            $vo_latLng[$v_key]['lat'] = $v_poi['airport_lat'];
                            $vo_latLng[$v_key]['lng'] = $v_poi['airport_lng'];
                        }else{
                            $vo_latLng[$v_key]['lat'] = "";
                            $vo_latLng[$v_key]['lng'] = "";
                        }

                        if(empty($vo_latLng[$v_key]['lat']) || empty($vo_latLng[$v_key]['lng'])){
                            unset($vo_latLng[$v_key]);
                        }
                    }
                    $vo_start_poi=array_shift($vo_latLng);
                    if(count($vo_latLng)>0){
                        $vo_end_poi=array_pop($vo_latLng);
                    }else{
                        $vo_end_poi=[
                            'lat'=>0,
                            'lng'=>0
                        ];
                    }
                    if(!empty($vo_start_poi['lat']) && !empty($vo_start_poi['lng']) && !empty($vo_end_poi['lat']) && !empty($vo_end_poi['lng'])){
                        $vo_start_poi = [[
                            'lat'=>$vo_start_poi['lat'],
                            'lng'=>$vo_start_poi['lng'],
                            'title'=>$vo_start_poi['poiname'],
                            'id'=>$vo_start_poi['id'],
                        ]];
                        $vo_end_poi = [[
                            'lat'=>$vo_end_poi['lat'],
                            'lng'=>$vo_end_poi['lng'],
                            'title'=>$vo_end_poi['poiname'],
                            'id'=>$vo_end_poi['id'],
                        ]];
                        $rc[$k]['hasLine'] = true;
                    }else{
                        $rc[$k]['hasLine'] = false;
                    }
                    foreach ($vo_latLng as $v_poi){
                        if(isset($v_poi['lat']) && isset($v_poi['lng']) && !empty($v_poi['lat']) && !empty($v_poi['lng'])){
                            $vo_ways_poi[] = ['lat'=>$v_poi['lat'],'lng'=>$v_poi['lng'],'title'=>$v_poi['title'],'id'=>$v_poi['id']];
                        }
                    }
                }
                $rc[$k]['start_poi'] = $vo_start_poi;
                $rc[$k]['end_poi'] = $vo_end_poi;
                $rc[$k]['ways_poi'] = $vo_ways_poi;

                if(!empty($y['cityname'])){
                    $city_id[$y['cityid']]=$y['cityname'];
                }
                $xq[$t]['thumb']='';
                $xq[$t]['address']='';
                $xq[$t]['lat']='';
                $xq[$t]['lng']='';
                $xq[$t]['show']=0;
                if($y['showticket']==0) $xq[$t]['ticket']='';
                if($y['showopen_time']==0) $xq[$t]['open_time']='';
                if($y['showticket_url']==0) $xq[$t]['ticket_url']='';
                if($y['showeng_introduce']==0) $xq[$t]['eng_introduce']='';
                if($y['showdescription']==0) $xq[$t]['description']='';
                if($y['showthumb']==0) $xq[$t]['thumb']='';
                if($y['showsource']==0) $xq[$t]['source']='';
                if($y['showaddress']==0) $xq[$t]['address']='';
                if($y['showgrade']==0) $xq[$t]['grade']='';
                if($y['showmobile']==0) $da['mobile']='';
                if($y['typeid']==2) $xq[$t]['title']=$y['cityname'];

                $xq[$t]['title']=$y['poiname'];

                if(in_array($y['activeType'],$includePoiActiveTypeList)){//   1POI    4酒店
                    if (!empty($y['poiid'])){
                        $poi=  db('poi')->alias('a')
                            ->where('a.id',$y['poiid'])
                            ->join('city c','c.id=a.groupid')
                            ->field('a.*,c.name as city_name')
                            ->find();
                        $xq[$t]['poi_content'] = !empty($y['poi_content'])?$y['poi_content']:$poi['introduce'];
                        if(!empty($y['poiImg'])){
                            $poiImgArr = explode(",",$y['poiImg']);
                            $images = !empty($poiImgArr) ? $poiImgArr : '';
                        }else{
                            $images=!empty($poi['thumb'])?explode(',',$poi['thumb']):'';
                        }

                        if ($images!=''){
                            $gg= array_filter($images);
                            $poi['thumb']=array_values($gg);
                        }else{
                            $poi['thumb']= '';
                        }

                        $da['mobile']=$poi['mobile'];
                        $xq[$t]['title']=$poi['name'];
                        $xq[$t]['eng_name']=$poi['eng_name'];
                        $xq[$t]['thumb']=$poi['thumb'];
                        $xq[$t]['address']=$poi['address'];
                        $xq[$t]['ticket']=$poi['ticket'];
                        $xq[$t]['open_time']=$poi['open_time'];
                        $xq[$t]['ticket_url']=$poi['ticket_url'];
                        $xq[$t]['eng_introduce']=$poi['eng_introduce'];
                        $xq[$t]['description']=$poi['description'];
                        $xq[$t]['grade']=$poi['grade'];
                        $xq[$t]['source']=$poi['source'];
                        $xq[$t]['lat']=$poi['lat'];
                        $xq[$t]['lng']=$poi['lng'];
                        $xq[$t]['show']=0;
                    }else{
                        $xq[$t]['poiid']='';
                        $xq[$t]['eng_name']='';

                        //增加【其它】中图片显示
                        $images=!empty($y['other_images'])?explode(',',$y['other_images']):'';
                        if ($images!=''){
                            $gg= array_filter($images);
                            $image_arr=array_values($gg) ;
                        }else{
                            $image_arr= '';
                        }
                        $xq[$t]['thumb']=$image_arr;
                    }
                }elseif($y['activeType']==2 || $y['activeType']==3 || $y['activeType']==6) {//   2接机    3送机   6其他
                    $xq[$t]['poi_content'] = '';
                    $xq[$t]['poiImg'] = '';
                }

                //索引
                $xq[$t]['name_id'] = "name_".$y['id'];
                if($y['showkey']==1){
                    $typeid = $y['typeid'];
                    if($typeid==3){
                        $keytitle = $y['poiname'];
                    }elseif($typeid==2){
                        $keytitle = $y['cityname'];
                    }else{
                        $keytitle = $y['title'];
                    }

                    $keytitle = $y['poiname'];

                    $activeKeyArr[] = [
                        'id'=>"name_".$y['id'],
                        'title'=>$keytitle,
                    ];
                }
            }
            $rc[$k]['xiangqing']=$xq;
            //索引数组
            $daytitle = $v['title'];
            if($v['title']!==''){
                if(substr($v['title'],0,1)==","){
                    $daytitle = substr($v['title'],1);
                    $rc[$k]['title']=$daytitle;
                }
            }

            $keyArr[] = [
                'day' => "DAY".($k+1)."：",
                'daytitle' => $daytitle,
                'day_key' => "day_".($k+1),
                'active' => $activeKeyArr
            ];
        }
        //是否有周边
        $da['hasExtra'] = $hasExtra;
        $city_id= array_values($city_id);

        for($i=0;$i<count($city_id);$i++){
            $da['city_name'].=$city_id[$i].',';
        }

        //首图banner
        if(empty($da['trip_banner'])){
            $da['trip_banner'] = 'https://kwibon-public-images.oss-cn-beijing.aliyuncs.com/custom/68fa01cd5691eb3282147a796baf1d98jpg';
        }
        //判断城市地图是否绘制
        //开始城市经纬度
        $start_city = [];
        //结束城市经纬度
        $end_city = [];
        //中间城市经纬度
        $ways_city = [];
        $hasLine = false;
        if(count($allcityLatLngs)>=2 && $da['show_city_map']==1){
            $hasLine  = true;
            $start_city = array_shift($allcityLatLngs);
            $end_city = array_pop($allcityLatLngs);
            $ways_city = $allcityLatLngs;
        }
        $da['keyArr']=$keyArr;
        $da['schedule']=$rc;
        $da['cityMap'] = [
            "hasLine"=>$hasLine,
            "start_city"=>$start_city,
            "end_city"=>$end_city,
            "ways_city"=>$ways_city,
        ];

        if($da['showpricedetail']==1){
            $da['totalPriceData'] = $this->getTripTotalPriceDataDetail($da);
        }else{
            $da['totalPriceData'] = ['total'=>0,'detail'=>[]];
        }
        //删除多余字段
        unset($da['total_sale_price'],
            $da['totalExtraPrice_rate'],
            $da['insurancePrice_rate'],
            $da['totalTicketPrice_rate'],
            $da['totalTransPrice_rate'],
            $da['totalDrivePrice_rate'],
            $da['totalHotelPrice_rate'],
            $da['totalAirportPrice_rate'],
            $da['totalAirportPrice'],
            $da['totalTransPrice'],
            $da['totalExtraPrice'],
            $da['totalTicketPrice'],
            $da['totalDrivePrice'],
            $da['totalHotelPrice'],
            $da['insuranceDetail'],
            $da['insurancePrice'],
            $da['total_price'],
            $da['section_json']
        );
        return json_encode(['msg'=>'查询成功','code'=>0,'data'=>$da]);
    }
    //获取行程报价明细
    public function getTripTotalPriceDataDetail($trip)
    {
        $totalPriceData = [
            'total'=>0,
            'detail'=>[]
        ];
        if(isset($trip['schedule']) && !empty($trip['schedule'])){
            $schedule = $trip['schedule'];
        }else{
            $schedule = db("schedule")->where(['groupid'=>$trip['trip_id']])->select();
        }
        $schedule_id = array_column($schedule,'id');
        if(empty($schedule_id)){
            return $totalPriceData;
        }else{
            $dayPrice = db("dayprice")->where(['groupid'=>['in',$schedule_id]])->select();
            //展示报价明细
            $airport_detail = [];
            $hotel_detail = [];
            $drive_detail = [];
            $ticket_detail = [];
            $extra_detail = [];
            foreach ($dayPrice as $day_k=>$day_value){
                $scheduleinfo= db("schedule")->field('time')->where(['id'=>$day_value['groupid']])->find();

                //机票费用明细
                if(!empty($day_value['airport_json'])){
                    $airport_json = json_decode($day_value['airport_json'],true);
                    foreach ($airport_json as $air_value){
                        if(isset($air_value[0]) && isset($air_value[1])){
                            $poiid = $air_value[0];
                            $airport = db('active')->where(['poiid'=>$poiid,'groupid'=>$day_value['groupid']])->find();
                            if(!empty($airport)){
                                $airport_detail[] = ['title'=>$airport['flight'].' '.$airport['title'],'desc'=>'','remark'=>'使用日期:'.date("m月d日",strtotime($scheduleinfo['time']))."\t".$air_value[1]];
                            }
                        }
                    }
                }

                //酒店费用明细
                if(!empty($day_value['hotelPrice'])){
                    $hotel = db('active')
                        ->where(['activeType'=>4,'groupid'=>$day_value['groupid']])
                        ->order("id desc")
                        ->find();
                    if(!empty($hotel)){
                        $hotel_detail[] = ['title'=>$hotel['poiname'],'desc'=>'','remark'=>"入住时间：".date("m月d日",strtotime($scheduleinfo['time']))."\t".$day_value['hotelDetail']];
                    }
                }
                //租车费用明细
                if(!empty($day_value['drivePrice'])){
                    $drive_detail[] = ['title'=>$day_value['driveDetail'],'desc'=>'','remark'=>'使用日期：'.date("m月d日",strtotime($scheduleinfo['time']))];
                }
                //门票费用明细
                if(!empty($day_value['ticketPrice'])){
                    $ticket_detail[] = ['title'=>$day_value['ticketDetailToC'],'desc'=>'','remark'=>'使用日期：'.date("m月d日",strtotime($scheduleinfo['time']))];
                }
                //附加费用明细
                if(!empty($day_value['extraPrice'])){
                    $extra_detail[] = ['title'=>$day_value['extraDetail'],'desc'=>'','remark'=>''];
                }
            }
            //机场报价
            $totalAirportPrice = floatval($trip['totalAirportPrice']);
            if(!empty($totalAirportPrice)) {
                $airport = [
                    'type' => 'airport',
                    'total' => ceil($trip['totalAirportPrice']*$trip['totalAirportPrice_rate']),
                    'title' => '机票',
                    'detail' => $airport_detail
                ];
            }else{
                $airport = [];
            }
            //酒店报价
            if(!empty($trip['totalHotelPrice'])) {
                $hotel = [
                    'type' => 'hotel',
                    'total' => ceil($trip['totalHotelPrice']*$trip['totalHotelPrice_rate']),
                    'title' => '酒店',
                    'detail' => $hotel_detail
                ];
            }else{
                $hotel = [];
            }
            //用车报价
            $car_time = [];//用车的准确时间集合
            $section_json = json_decode($trip['section_json'],true);
            if(!empty($section_json) && $trip['start_go_time']>0){
                foreach ($section_json as $section){
                    $startday = $section['start'] ?? -1;
                    $endday = $section['end'] ?? -1;
                    if(!empty($startday)) $startday = explode('-',$startday)[0] ?? -1;
                    if(!empty($endday)) $endday = explode('-',$endday)[0] ?? -1;
                    if($startday>-1 && $endday > -1 && $startday<=$endday){
                        for ($i=$startday;$i<=$endday;$i++){
                            $car_time[] = date('Y-m-d',$i*24*3600+$trip['start_go_time']);
                        }
                    }
                }
            }
            $car_detail_title = "";
            if(!empty($car_time)){
                $start_month = 0;
                $start_time = 0;
                $cur_day = "";
                foreach ($car_time as $car_key=>$car_value){
                    $start_day = date("m月d日",strtotime($car_value));
                    if($start_time+3600*24==strtotime($car_value) && $car_key>0){
                        if($car_key==count($car_time)-1){
                            $car_detail_title .= '-';
                            $car_detail_title .= $start_month==date("m",strtotime($car_value))?date("d日",strtotime($car_value)):date("m月d日",strtotime($car_value));
                        }
                    }elseif($car_key==0){
                        $start_month = date("m",strtotime($car_value));
                        $cur_day = $start_day;
                        $car_detail_title .= $start_day;
                    }else{
                        $car_prev_value = $car_time[$car_key-1];
                        $prev_day = $start_month==date("m",strtotime($car_prev_value))?date("d日",strtotime($car_prev_value)):date("m月d日",strtotime($car_prev_value));
                        if($prev_day!=$cur_day){
                            $car_detail_title .= '-';
                            $car_detail_title .= $prev_day;
                        }
                        $car_detail_title .= '+';
                        $cur_day = $start_month==date("m",strtotime($car_value))?date("d日",strtotime($car_value)):date("m月d日",strtotime($car_value));
                        $car_detail_title .= $cur_day;
                    }
                    $start_time = strtotime($car_value);
                }
            }
            if(!empty($trip['totalTransPrice'])) {
                $car = [
                    'type'=>'car',
                    'total'=>ceil($trip['totalTransPrice']*$trip['totalTransPrice_rate']),
                    'title'=>'用车',
                    'detail'=>[
                        ['title'=>$car_detail_title,'desc'=>'','remark'=>'']
                    ]
                ];
            }else{
                $car = [];
            }

            //门票报价
            if(!empty($trip['totalTicketPrice'])) {
                $ticket = [
                    'type' => 'ticket',
                    'total' => ceil($trip['totalTicketPrice']*$trip['totalTicketPrice_rate']),
                    'title' => '门票',
                    'detail' => $ticket_detail
                ];
            }else{
                $ticket = [];
            }
            //租车报价
            if(!empty($trip['totalDrivePrice'])){
                $drive = [
                    'type'=>'drive',
                    'total'=>ceil($trip['totalDrivePrice']*$trip['totalDrivePrice_rate']),
                    'title'=>'租车',
                    'detail'=>$drive_detail
                ];
            }else{
                $drive = [];
            }
            //保险报价
            if(!empty($trip['insurancePrice'])){
                $insurance = [
                    'type'=>'insurance',
                    'total'=>ceil($trip['insurancePrice']*$trip['insurancePrice_rate']),
                    'title'=>'保险',
                    'detail'=>[
                        ['title'=>$trip['insuranceDetail'],'desc'=>'','remark'=>''],
                    ]
                ];
            }else{
                $insurance = [];
            }
            if(!empty($trip['totalExtraPrice'])){
                //附加费用
                $extra = [
                    'type'=>'extra',
                    'total'=>ceil($trip['totalExtraPrice']*$trip['totalExtraPrice_rate']),
                    'title'=>'附加',
                    'detail'=>$extra_detail
                ];
            }else{
                $extra = [];
            }
            $totalPriceDetail = [];
            array_push($totalPriceDetail,$airport,$hotel,$car,$drive,$ticket,$insurance,$extra);
            $totalPriceDetail = array_values(array_filter($totalPriceDetail));
            $totalPriceData = [
                'total'=>$trip['total_sale_price'],
                'detail'=>$totalPriceDetail
            ];
            return $totalPriceData;
        }
    }

    //获取国家电话区号
    public function getCountryPhoneCode()
    {
        return [
            ['country'=>'china','code'=>'+86','countryName'=>'中国','codeName'=>'中国+86'],
            ['country'=>'America','code'=>'+1','countryName'=>'美国','codeName'=>'美国+1'],
            ['country'=>'china','code'=>'+886','countryName'=>'中国台湾','codeName'=>'中国台湾+886'],
            ['country'=>'china','code'=>'+852','countryName'=>'中国香港','codeName'=>'中国香港+852'],
            ['country'=>'china','code'=>'+853','countryName'=>'中国澳门','codeName'=>'中国澳门+853'],
            ['country'=>'','code'=>'+','countryName'=>'','codeName'=>'其他+'],
        ];
    }

    //获取全局节点类型数组
    public function getGlobalActiveTypeList($includePoiAndHotel=true)
    {
        $poiClassifyList = db('classify')
            ->field('classify_id as id,classify_name as name')
            ->where(['is_use'=>1,'classify_id'=>['gt',10]])
            ->select();
        $global_active_type_arr = array_column($poiClassifyList,'id');
        if($includePoiAndHotel){
            array_unshift($global_active_type_arr,4);
            array_unshift($global_active_type_arr,1);
        }

        return $global_active_type_arr;
    }

    //获取关联的expedia酒店
    public function getExpediaHotel(Request $request)
    {
        $ids = $request->param('ids','');
        if(empty($ids)){
            $active_id = $request->param('active_id','');
            if(empty($active_id)){
                $trip_id = $request->param('trip_id','');
                if(empty($trip_id)){
                    return json(['code'=>0,'msg'=>'缺少参数trip_id']);
                }else{
                    $ids = (new TripActiveHotel())->where([
                        'trip_id'   => $trip_id,
                        'is_delete' =>   0,
                    ])->column('id');
                }
            }else{
                $ids = (new TripActiveHotel())->where([
                    'active_id' =>  $active_id,
                    'is_delete' =>  0,
                ])->column('id');
            }
        }else{
            $ids = explode(',',$ids);
        }

        if(empty($ids)) json(['code'=>0,'msg'=>'缺少参数ids']);

        $res = (new TripActiveHotel())->where([
            'id'        =>  ['in',$ids],
            'is_delete' =>  0,
        ])->order('create_time asc')->select();
        if($res!==false){
            foreach ($res as $key=>$value){
                $occupancy = explode('|',$value['occupancy']);
                $totalPerson = 0;
                foreach ($occupancy as $k=>$v){
                    if(empty($v)) continue;
                    $person = explode('-',$v);
                    $adult = $person[0] ?? 0;
                    $childrenAge = $person[1] ?? '';
                    $children = count(explode(',',$childrenAge));
                    $totalPerson += $adult + $children;
                }
                $res[$key]['occupancy_title'] = count($occupancy) .'间房，'.$totalPerson.'个人';
            }
            return json(['code'=>0,'msg'=>'获取成功','count'=>count($res),'data'=>$res]);
        }else{
            return json(['code'=>-1,'msg'=>'添加失败']);
        }
    }
}